﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;

using Ldt.CaseRetrievalApp.ESlibrary;
using Nest;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Sunny.UI;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using Microsoft.Extensions.Configuration;
using System.Text.RegularExpressions;

namespace Ldt.CaseRetrievalApp
{
    public partial class FormCaseRetrieval : UIForm
    {
        public FormCaseRetrieval()
        {
            InitializeComponent();
            httpHelper = new WebClient();
        }
        private WebClient httpHelper { get; }

        /// <summary>
        /// 案件检索服务的地址
        /// </summary>
        private string AppUrl { get; set; }

        /// <summary>
        /// Es检索服务地址
        /// </summary>
        private IElasticClient ElasticClient { get; set; }

        private void FormCaseRetrieval_Load(object sender, EventArgs e)
        {
            var configuration = new ConfigurationBuilder().SetBasePath(System.AppContext.BaseDirectory).AddJsonFile("appsettings.json", true, true).Build();

            var centerAddress = configuration["appSettings:setting_center_address"];
            
            Regex urlReg =new Regex(@"(http|https)://[^\s]*");
            if (urlReg.IsMatch(centerAddress))
            {
                var centerUri = new Uri(centerAddress);
                centerConfigTextBox.Text = centerUri.Host;
                portTextBox.Text = centerUri.Port.ToString();
            }

        }

        /// <summary>
        /// 配置中心地址应用
        /// </summary>
        private void applyButton_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(centerConfigTextBox.Text) && !string.IsNullOrWhiteSpace(portTextBox.Text))
            {
                string url = "http://" + centerConfigTextBox.Text.Trim() + ":" + portTextBox.Text.Trim() + "/center/settings/v2/SystemAPI/application/api/code/Ldt.ElementCenterInfoQuery?courtcode=";
                string esurl = "http://" + centerConfigTextBox.Text.Trim() + ":" + portTextBox.Text.Trim() + "/center/settings/v2/SystemAPI/application/api/code/ES.ElementCenter?courtcode=";
                string msg = GetHttpDataTextWebClient(url);
                string esmsg = GetHttpDataTextWebClient(esurl);
                if (!string.IsNullOrWhiteSpace(msg))
                {
                    JObject resultJ = JObject.Parse(msg);
                    //var body = resultJ.Value<JObject>("body");
                    var body = resultJ.SelectToken("body").First();
                    var ip = body.Value<string>("serverIp");
                    var port = body.Value<string>("value");
                    AppUrl = "http://" + ip + ":" + port;
                    applyButton.Enabled = false;
                }
                if (!string.IsNullOrWhiteSpace(esmsg))
                {
                    JObject resultJ = JObject.Parse(esmsg);
                    //var body = resultJ.Value<JObject>("body");
                    var body = resultJ.SelectToken("body").First();
                    var ip = body.Value<string>("serverIp");
                    var port = body.Value<string>("value");
                    string EsUrl = "http://" + ip + ":" + port;
                    ESSever eSSever = new ESSever(EsUrl);
                    ElasticClient = eSSever.ElasticLinqClient;
                }
            }
            else
            {
                MessageBox.Show("请输入有效的配置中心地址！");
                centerConfigTextBox.Focus();
            }
        }

        /// <summary>
        /// 要素中心字典检索按钮Click事件
        /// </summary>
        private void dicSearchButton_Click(object sender, EventArgs e)
        {
            if(AppUrl==null)
            {
                MessageBox.Show("请应用配置中心地址！");
                return;
            }
            if (!string.IsNullOrWhiteSpace(dicCaseTypeTextBox.Text))
            {
                var httpmesg = GetHttpDataTextWebClient(AppUrl + $"/api/casedataservice/getconvertdictionaydata?systemCode=11&caseType={dicCaseTypeTextBox.Text.Trim()}");
                if (!string.IsNullOrWhiteSpace(httpmesg))
                {
                    JObject resultJ = JObject.Parse(httpmesg);
                    string code = resultJ.Value<string>("code");
                    string mesg = resultJ.Value<string>("message");
                    if (code == "0")
                    {
                        MessageBox.Show("数据请求错误！" + httpmesg);
                    }
                    else
                    {
                        var bo = resultJ.SelectToken("body");
                        if (bo != null)
                        {
                            dicRichTextBox.Text = ConvertJsonString(JsonConvert.SerializeObject(bo));
                        }
                        else
                        {
                            MessageBox.Show("没有找到主体信息，接口返回消息为：" + mesg);
                        }

                    }

                }
            }

        }

        /// <summary>
        /// 要素中心检索按钮Click事件
        /// </summary>
        private void elementSearchButton_Click(object sender, EventArgs e)
        {
            if(AppUrl==null)
            {
                MessageBox.Show("请应用配置中心地址！");
                return;
            }
            if (!string.IsNullOrWhiteSpace(elementCaseIdTextBox.Text))
            {
                var httpmesg = GetHttpDataTextWebClient(AppUrl + $"/api/casepartdata/getcaseelementdata?systemCode=11&caseId={elementCaseIdTextBox.Text.Trim()}");
                if (!string.IsNullOrWhiteSpace(httpmesg))
                {
                    JObject resultJ = JObject.Parse(httpmesg);
                    string code = resultJ.Value<string>("code");
                    string mesg = resultJ.Value<string>("message");

                    if (code == "0")
                    {
                        MessageBox.Show("数据请求错误！" + httpmesg);
                    }
                    else
                    {
                        var bo = resultJ.SelectToken("body");
                        if (bo != null)
                        {
                            var xmlcontent = bo.Value<string>("content");
                            XmlDocument document = new XmlDocument();
                            document.LoadXml(xmlcontent.ToString());
                            // document.OuterXml;
                            elementRichTextBox.Text = ConvertToFormatXml(document);
                        }
                        else
                        {
                            MessageBox.Show("没有找到主体信息，接口返回消息为：" + mesg);
                        }
                    }

                }
            }
        }

        /// <summary>
        /// 案件来源检索按钮Click事件
        /// </summary>
        private void sourceSearchButton_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(sourceCaseIdTextBox.Text))
            {
                var httpmesg = GetHttpDataTextWebClient(AppUrl + $"/api/casepartdata/getcasedatasourcelist?systemCode=11&caseId={sourceCaseIdTextBox.Text.Trim()}");
                if (!string.IsNullOrWhiteSpace(httpmesg))
                {
                    JObject resultJ = JObject.Parse(httpmesg);
                    string code = resultJ.Value<string>("code");
                    string mesg = resultJ.Value<string>("message");
                    if (code == "0")
                    {
                        MessageBox.Show("数据请求错误！" + httpmesg);
                    }
                    else
                    {
                        var bo = resultJ.SelectToken("body");
                        if (bo != null)
                        {
                            XmlDocument document = new XmlDocument();
                            document.LoadXml(bo.ToString());
                            sourceRichTextBox.Text = ConvertToFormatXml(document);// document.OuterXml;
                        }
                        else
                        {
                            MessageBox.Show("没有找到主体信息，接口返回消息为：" + mesg);
                        }

                    }

                }
            }
        }

        /// <summary>
        /// Es列表查询按钮Click事件
        /// </summary>
        private void listSeatchButton_Click(object sender, EventArgs e)
        {
            if (ElasticClient == null)
            {
                MessageBox.Show("请应用配置中心地址！");
                return;
            }
            dataResultLabel.Text = "结果：*";
            //string ip = "192.168.1.21:16002";
            //string ip = "http://192.168.1.21:9600";
            //var allindexs = ElasticClient.Indices.Stats();
            //var indextemp = allindexs.Indices.GroupBy(k => Regex.Match(k.Key, @"(^|\s*\r\s*)(?!\.|%)[^\r]*(?=\-\d)").Value).Where(a => !string.IsNullOrWhiteSpace(a.Key)).Select(a => a.Key).OrderBy(a => a).ToArray();
            QueryContainer termQuerycase = null;
            //查询案件ID不为空
            if (!string.IsNullOrWhiteSpace(listCaseIdTextBox.Text))
            {
                termQuerycase = new MatchPhraseQuery() { Field = "anjid", Query = listCaseIdTextBox.Text };
            }
            //查询案号不为空
            if (!string.IsNullOrWhiteSpace(listCaseCodeTextBox.Text))
            {
                QueryContainer termQuerycode = new MatchPhraseQuery() { Field = "anh", Query = listCaseCodeTextBox.Text };
                termQuerycase = termQuerycase == null ? termQuerycode : termQuerycode && termQuerycase;
            }

            if (termQuerycase == null)
            {
                MessageBox.Show("ES数据检索，案件ID或者案号两者必须其中一个有数据！");
                return;
            }
            listSeatchButton.Enabled = false;
            var start = ElasticClient.Indices.Stats();
            var response = ElasticClient.Search<dynamic>(s => s
            .Index("ldtelementcentercommon") //or specify index via settings.DefaultIndex("mytweetindex");
            .From(0)
            .Size(10)
            .Query(q => termQuerycase)
            );
            dataResultLabel.Text = "结果：" + response.Documents.Count;
            string jsonstr = Newtonsoft.Json.JsonConvert.SerializeObject(response.Documents, Newtonsoft.Json.Formatting.Indented);
            listRichTextBox.Text = jsonstr;
            listSeatchButton.Enabled = true;
        }



        /// <summary>
        /// 字符串内容格式化输出
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private string ConvertJsonString(string str)
        {
            //格式化json字符串
            JsonSerializer serializer = new JsonSerializer();
            TextReader tr = new StringReader(str);
            JsonTextReader jtr = new JsonTextReader(tr);
            object obj = serializer.Deserialize(jtr);
            if (obj != null)
            {
                StringWriter textWriter = new StringWriter();
                JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)
                {
                    Formatting = Newtonsoft.Json.Formatting.Indented,
                    Indentation = 4,
                    IndentChar = ' '
                };
                serializer.Serialize(jsonWriter, obj);
                return textWriter.ToString();
            }
            else
            {
                return str;
            }
        }

        /// <summary>
        /// 格式化XML文件
        /// </summary>
        /// <param name="xml"></param>
        /// <returns></returns>
        private static string ConvertToFormatXml(XmlDocument xml)
        {
            XmlDocument xd = xml as XmlDocument;
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            XmlTextWriter xtw = null;
            try
            {
                xtw = new XmlTextWriter(sw);
                xtw.Formatting = System.Xml.Formatting.Indented;
                xtw.Indentation = 1;
                xtw.IndentChar = '\t';
                xd.WriteTo(xtw);
            }
            finally
            {
                if (xtw == null)
                    xtw.Close();
            }
            return sb.ToString();
        }

        private string GetHttpDataTextWebClient(string url)
        {
            try
            {
                string responsetext = "";
                var stream = httpHelper.OpenRead(url);
                using (StreamReader streamReader = new StreamReader(stream))
                {
                    responsetext = streamReader.ReadToEnd();
                }
                return responsetext;
            }
            catch (Exception ex)
            {
                MessageBox.Show("请求失败！请检查地址！" + ex.Message);

            }
            return "";
        }

        private string GetHttpDataText(string url)
        {
            // 创建一个HTTP请求  
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "get";
            var response = (HttpWebResponse)request.GetResponse();
            var myreader = new StreamReader(response.GetResponseStream());
            var responseText = myreader.ReadToEnd();
            myreader.Close();
            return responseText;
        }

        
    }
}
